package com.asen.commons.concurrent;

import java.util.Map;
import java.util.WeakHashMap;

/**
 * 缓存线程上下文信息
 *
 * @author Gary
 * @version 1.0
 * @date 2019-10-24
 */
public class ThreadLocalCache {

    private static final int INITIAL_CAPACITY = 256;

    private final static String AUTH_TOKEN = "AUTH_TOKEN";

    private final static String TENANT_ID = "TENANT_ID";

    private final static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>() {
        @Override
        protected Map<String, Object> initialValue() {
            return new WeakHashMap<String, Object>(INITIAL_CAPACITY);
        }
    };

    public static void put(String key, Object value) {
        Map<String, Object> map = threadLocal.get();
        map.put(key, value);
    }

    public static Object get(String key) {
        Map<String, Object> map = threadLocal.get();
        return map.get(key);
    }

    public static void remove(String key) {
        Map<String, Object> map = threadLocal.get();
        map.remove(key);
    }

    public static Map<String, Object> getAll() {
        return threadLocal.get();
    }

    public static void clear() {
        threadLocal.get().clear();
    }

    public static String getString(String key) {
        Object o = get(key);
        if (o == null) {
            return null;
        }
        return o.toString();
    }

    public static Long getLong(String key) {
        Object o = get(key);
        if (o == null) {
            return null;
        }
        return Long.valueOf(o.toString());
    }

    public static String getAuthToken() {
        return (String) get(AUTH_TOKEN);
    }

    public static void setAuthToken(String token) {
        put(AUTH_TOKEN, token);
    }

    public static void removeAuthToken() {
        remove(AUTH_TOKEN);
    }

    public static Long getTenantId() {
        return (Long) get(TENANT_ID);
    }

    public static void setTenantId(Long tenantId) {
        put(TENANT_ID, tenantId);
    }

    public static void removeTenantId() {
        remove(TENANT_ID);
    }

}
